import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:labcloud_app/models/user_model.dart';
import 'dart:async';

class LoginRegister extends StatefulWidget {
  const LoginRegister({super.key});

  @override
  State<LoginRegister> createState() => _LoginRegisterState();
}

class _LoginRegisterState extends State<LoginRegister>
    with SingleTickerProviderStateMixin {
  late TabController _tabController;
  bool _isLoginMode = true; // true为登录模式，false为注册模式
  bool _isPasswordLogin = true; // true为密码登录，false为验证码登录
  bool _isSendingCode = false; // 是否正在发送验证码
  int _countdown = 0; // 倒计时时间
  Timer? _timer; // 倒计时定时器，改为可空类型

  // 控制器
  final TextEditingController _usernameController = TextEditingController();
  final TextEditingController _passwordController = TextEditingController();
  final TextEditingController _emailController = TextEditingController();
  final TextEditingController _codeController = TextEditingController();
  final TextEditingController _confirmPasswordController =
  TextEditingController();

  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: 2, vsync: this);
  }

  @override
  void dispose() {
    _tabController.dispose();
    _usernameController.dispose();
    _passwordController.dispose();
    _emailController.dispose();
    _codeController.dispose();
    _confirmPasswordController.dispose();
    // 取消定时器
    _timer?.cancel(); // 使用?.操作符安全地调用cancel
    super.dispose();
  }

  // 发送验证码
  void _sendVerificationCode() async {
    final userModel = Provider.of<UserModel>(context, listen: false);
    
    if (_emailController.text.isEmpty) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('请输入邮箱地址')),
      );
      return;
    }
    
    // 验证邮箱格式
    if (!RegExp(r'^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$').hasMatch(_emailController.text)) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('请输入正确的邮箱格式')),
      );
      return;
    }
    
    setState(() {
      _isSendingCode = true;
    });
    
    try {
      await userModel.emailCode(email: _emailController.text.trim());
      
      // 开始倒计时
      setState(() {
        _countdown = 60;
        _isSendingCode = false;
      });
      
      // 启动倒计时定时器
      _timer = Timer.periodic(const Duration(seconds: 1), (timer) {
        setState(() {
          if (_countdown > 0) {
            _countdown--;
          } else {
            _timer?.cancel();
          }
        });
      });
      
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('验证码已发送，请查收邮箱')),
      );
    } catch (e) {
      setState(() {
        _isSendingCode = false;
      });
      
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('验证码发送失败，请稍后重试')),
      );
    }
  }

  // 切换登录方式
  void _toggleLoginMethod() {
    setState(() {
      _isPasswordLogin = !_isPasswordLogin;
    });
  }

  // 登录处理
  void _handleLogin() async {
    final userModel = Provider.of<UserModel>(context, listen: false);
    
    if (_isPasswordLogin) {
      // 密码登录
      if (_usernameController.text.isEmpty ||
          _passwordController.text.isEmpty) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(content: Text('请输入用户名和密码')),
        );
        return;
      }
      
      // 显示加载提示
      showDialog(
        context: context,
        barrierDismissible: false,
        builder: (BuildContext context) {
          return const Center(
            child: CircularProgressIndicator(),
          );
        },
      );
      
      try {
        await userModel.login(
          username: _usernameController.text.trim(),
          password: _passwordController.text.trim()
        );
        
        // 隐藏加载提示
        Navigator.of(context).pop();
        
        // 登录成功，返回上一页
        Navigator.of(context).pop(true);
      } catch (e) {
        // 隐藏加载提示
        Navigator.of(context).pop();
        
        // 登录失败
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(content: Text('登录失败，请检查用户名和密码')),
        );
      }
    } else {
      // 验证码登录
      if (_emailController.text.isEmpty || _codeController.text.isEmpty) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(content: Text('请输入邮箱和验证码')),
        );
        return;
      }
      
      // 显示加载提示
      showDialog(
        context: context,
        barrierDismissible: false,
        builder: (BuildContext context) {
          return const Center(
            child: CircularProgressIndicator(),
          );
        },
      );
      
      try {
        await userModel.loginByEmail(
          email: _emailController.text.trim(),
          code: _codeController.text.trim()
        );
        
        // 隐藏加载提示
        Navigator.of(context).pop();
        
        // 登录成功，返回上一页
        Navigator.of(context).pop(true);
      } catch (e) {
        // 隐藏加载提示
        Navigator.of(context).pop();
        
        // 登录失败
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(content: Text('登录失败，请检查邮箱和验证码')),
        );
      }
    }
  }

  // 注册处理
  void _handleRegister() async {
    // TODO: 实现注册逻辑
    if (_usernameController.text.isEmpty ||
        _emailController.text.isEmpty ||
        _passwordController.text.isEmpty ||
        _confirmPasswordController.text.isEmpty) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('请填写所有必填项')),
      );
      return;
    }

    if (_passwordController.text != _confirmPasswordController.text) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('两次输入的密码不一致')),
      );
      return;
    }
    
    // 显示加载提示
    showDialog(
      context: context,
      barrierDismissible: false,
      builder: (BuildContext context) {
        return const Center(
          child: CircularProgressIndicator(),
        );
      },
    );
    
    try {
      final userModel = Provider.of<UserModel>(context, listen: false);
      
      // 这里应该调用注册API，暂时使用登录模拟
      await Future.delayed(const Duration(seconds: 1));
      
      // 隐藏加载提示
      Navigator.of(context).pop();
      
      // 注册成功后返回上一页
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('注册成功')),
      );
      Navigator.of(context).pop(true);
    } catch (e) {
      // 隐藏加载提示
      Navigator.of(context).pop();
      
      // 注册失败
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('注册失败，请稍后重试')),
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('登录/注册'),
        centerTitle: true,
      ),
      body: SingleChildScrollView(
        padding: const EdgeInsets.all(20),
        child: Column(
          children: [
            // 登录/注册切换标签
            Container(
              height: 60,
              padding: const EdgeInsets.all(6),
              decoration: BoxDecoration(
                color: Colors.grey[100],
                borderRadius: BorderRadius.circular(30),
              ),
              child: TabBar(
                controller: _tabController,
                indicator: BoxDecoration(
                  borderRadius: BorderRadius.circular(24),
                  color: Colors.blue,
                  boxShadow: [
                    BoxShadow(
                      color: Colors.blue.withOpacity(0.3),
                      blurRadius: 8,
                      offset: const Offset(0, 2),
                    ),
                  ],
                ),
                labelColor: Colors.white,
                unselectedLabelColor: Colors.black54,
                labelStyle: const TextStyle(
                  fontSize: 16,
                  fontWeight: FontWeight.bold,
                ),
                unselectedLabelStyle: const TextStyle(
                  fontSize: 16,
                  fontWeight: FontWeight.normal,
                ),
                tabs: const [
                  Tab(text: '登录'),
                  Tab(text: '注册'),
                ],
              ),
            ),
            const SizedBox(height: 30),

            // TabBar 内容
            SizedBox(
              height: 500,
              child: TabBarView(
                controller: _tabController,
                children: [
                  // 登录页面
                  _buildLoginPage(),
                  // 注册页面
                  _buildRegisterPage(),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  // 构建登录页面
  Widget _buildLoginPage() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.stretch,
      children: [
        // 登录方式切换按钮
        _buildLoginMethodToggle(),
        const SizedBox(height: 20),

        // 用户名/邮箱输入框
        TextField(
          controller: _isPasswordLogin ? _usernameController : _emailController,
          decoration: InputDecoration(
            labelText: _isPasswordLogin ? '用户名' : '邮箱',
            border: const OutlineInputBorder(
              borderRadius: BorderRadius.all(Radius.circular(30)),
            ),
            prefixIcon: Icon(
              _isPasswordLogin ? Icons.person : Icons.email,
            ),
          ),
        ),
        const SizedBox(height: 20),

        // 密码或验证码输入框
        _isPasswordLogin
            ? TextField(
          controller: _passwordController,
          obscureText: true,
          decoration: const InputDecoration(
            labelText: '密码',
            border: OutlineInputBorder(
              borderRadius: BorderRadius.all(Radius.circular(30)),
            ),
            prefixIcon: Icon(Icons.lock),
          ),
        )
            : Row(
          children: [
            Expanded(
              child: TextField(
                controller: _codeController,
                decoration: const InputDecoration(
                  labelText: '验证码',
                  border: OutlineInputBorder(
                    borderRadius: BorderRadius.all(Radius.circular(30)),
                  ),
                  prefixIcon: Icon(Icons.lock),
                ),
              ),
            ),
            const SizedBox(width: 10),
            ElevatedButton(
              onPressed: _isSendingCode || _countdown > 0 ? null : _sendVerificationCode,
              style: ElevatedButton.styleFrom(
                backgroundColor: Colors.blue,
                foregroundColor: Colors.white,
                padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 16),
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(30),
                ),
              ),
              child: _isSendingCode
                  ? const SizedBox(
                      width: 20,
                      height: 20,
                      child: CircularProgressIndicator(
                        strokeWidth: 2,
                        valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
                      ),
                    )
                  : Text(_countdown > 0 ? '$_countdown秒后重发' : '发送验证码'),
            ),
          ],
        ),
        const SizedBox(height: 30),

        // 登录按钮
        _buildActionButton('登录', _handleLogin),
      ],
    );
  }

  // 构建登录方式切换控件（优化版）
  Widget _buildLoginMethodToggle() {
    return Container(
      height: 50,
      decoration: BoxDecoration(
        color: Colors.grey[100],
        borderRadius: BorderRadius.circular(25),
      ),
      child: Row(
        children: [
          Expanded(
            child: GestureDetector(
              onTap: () {
                if (!_isPasswordLogin) {
                  setState(() {
                    _isPasswordLogin = true;
                  });
                }
              },
              child: AnimatedContainer(
                duration: const Duration(milliseconds: 300),
                margin: EdgeInsets.all(_isPasswordLogin ? 2 : 5),
                decoration: BoxDecoration(
                  color: _isPasswordLogin ? Colors.blue : Colors.transparent,
                  borderRadius: BorderRadius.circular(25),
                ),
                alignment: Alignment.center,
                child: Text(
                  '账号密码',
                  style: TextStyle(
                    color: _isPasswordLogin ? Colors.white : Colors.black54,
                    fontWeight: _isPasswordLogin ? FontWeight.bold : FontWeight.normal,
                  ),
                ),
              ),
            ),
          ),
          Expanded(
            child: GestureDetector(
              onTap: () {
                if (_isPasswordLogin) {
                  setState(() {
                    _isPasswordLogin = false;
                  });
                }
              },
              child: AnimatedContainer(
                duration: const Duration(milliseconds: 300),
                margin: EdgeInsets.all(!_isPasswordLogin ? 2 : 5),
                decoration: BoxDecoration(
                  color: !_isPasswordLogin ? Colors.blue : Colors.transparent,
                  borderRadius: BorderRadius.circular(25),
                ),
                alignment: Alignment.center,
                child: Text(
                  '邮箱验证码',
                  style: TextStyle(
                    color: !_isPasswordLogin ? Colors.white : Colors.black54,
                    fontWeight: !_isPasswordLogin ? FontWeight.bold : FontWeight.normal,
                  ),
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  // 构建操作按钮（登录/注册）
  Widget _buildActionButton(String text, VoidCallback onPressed) {
    return Container(
      height: 56,
      padding: const EdgeInsets.all(4),
      decoration: BoxDecoration(
        color: Colors.grey[100],
        borderRadius: BorderRadius.circular(28),
      ),
      child: ElevatedButton(
        onPressed: onPressed,
        style: ElevatedButton.styleFrom(
          backgroundColor: Colors.blue,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(28),
          ),
          padding: EdgeInsets.zero,
          elevation: 0,
        ),
        child: Text(
          text,
          style: const TextStyle(
            fontSize: 18,
            color: Colors.white,
            fontWeight: FontWeight.bold,
          ),
        ),
      ),
    );
  }

  // 构建注册页面
  Widget _buildRegisterPage() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.stretch,
      children: [
        // 用户名输入框
        TextField(
          controller: _usernameController,
          decoration: const InputDecoration(
            labelText: '用户名',
            border: OutlineInputBorder(
              borderRadius: BorderRadius.all(Radius.circular(30)),
            ),
            prefixIcon: Icon(Icons.person),
          ),
        ),
        const SizedBox(height: 20),

        // 邮箱输入框
        TextField(
          controller: _emailController,
          decoration: const InputDecoration(
            labelText: '邮箱',
            border: OutlineInputBorder(
              borderRadius: BorderRadius.all(Radius.circular(30)),
            ),
            prefixIcon: Icon(Icons.email),
          ),
        ),
        const SizedBox(height: 20),

        // 密码输入框
        TextField(
          controller: _passwordController,
          obscureText: true,
          decoration: const InputDecoration(
            labelText: '密码',
            border: OutlineInputBorder(
              borderRadius: BorderRadius.all(Radius.circular(30)),
            ),
            prefixIcon: Icon(Icons.lock),
          ),
        ),
        const SizedBox(height: 20),

        // 确认密码输入框
        TextField(
          controller: _confirmPasswordController,
          obscureText: true,
          decoration: const InputDecoration(
            labelText: '确认密码',
            border: OutlineInputBorder(
              borderRadius: BorderRadius.all(Radius.circular(30)),
            ),
            prefixIcon: Icon(Icons.lock),
          ),
        ),
        const SizedBox(height: 30),

        // 注册按钮
        _buildActionButton('注册', _handleRegister),
      ],
    );
  }
}
